//
//  TimeIntervalManagerViewController.swift
//  mggz
//
//  Created by QinWei on 2018/1/29.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import ObjectMapper
import SVProgressHUD
import Moya

class TimeIntervalManagerViewController: UIViewController {
    var timeAlert:TWLAlertView?
    
    var addAlert:CustomDialog?
   // var datePicker:UIDatePicker?
    var guid:String?
    var custom : LCTimeSelectView?
    var isTomorror:Bool?
    var startTime:String?
    var endTime:String?
    var isedit = false // add
    var selectItem:Int?
    var emptyStr = "\n\n\n\n\n"
    lazy var actionsheet:UIAlertController = {
        var alert = UIAlertController(title: self.emptyStr, message: "", preferredStyle: .actionSheet)
        alert.view.addSubview(self.datePicker)
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        let okAction = UIAlertAction(title: "确定", style: .default, handler: { (action) in
            print("确定")
            self.custom?.pmTimeButton.setTitle(self.endTime, for: .normal)
            self.custom?.amTimeButton.setTitle(self.startTime, for: .normal)
        })
        alert.view.addSubview(self.datePicker)
        alert.addAction(cancelAction)
        alert.addAction(okAction)
        return alert
    }()
    
    lazy var qdDelDialog:UIAlertController = {
        var view = UIAlertController(title: "提示", message: "确定要删除该时段吗？", preferredStyle: .alert)
        let cancal = UIAlertAction(title: "取消", style: .cancel, handler: { (action) in
            
        })
        let submit = UIAlertAction(title: "确定", style: .default, handler: { (action) in
            self.operateSubmit([String:String](),operatetype:3)
        })
        view.addAction(cancal)
        view.addAction(submit)
        return view
    }()
    
    lazy var timeDialog:SelectTimeDialog = {
        var view = SelectTimeDialog.initWithClick(frame: CGRect.zero, _cancelclick: {
            print("徐晓")
            if self.selectItemModel?.IsDefault == true{
                //self.timeDialog.titlename.text = "默认时段"
                QWTextonlyHud("默认时段不能删除", target: self.view)
                //self.timeDialog.show()
            }else{
                self.isedit = false
                self.present(self.qdDelDialog, animated: true, completion: nil)
            }
            
            
        }, _submitclick: { (data) in
            guard let bean = data as? [String:String] else{
                return
            }
            //QWTextWithStatusHud("正在处理中...", target: self.timeDialog.contentview)
            self.operateSubmit(bean,operatetype:2)
        })
        view.autoClose = false
        
        return view
    }()
    
    
    func operateSubmit(_ dic:[String:String],operatetype operatetype:Int){
        
        if isedit{
            QWTextWithStatusHud("正在处理中...", target: self.timeDialog.contentview)
        }else{
            QWTextWithStatusHud("正在处理中...", target: self.view)
        }
        
            var id = self.timeArray[self.selectItem!].ID ?? ""
            var workTimeQuantumName = self.timeArray[self.selectItem!].WorkTimeQuantumName ?? ""
            var s,e:String?
            var IsLastDay = false
        
            if dic.isEmpty{
                s = self.timeArray[self.selectItem!].BeginTime ?? ""
                e = self.timeArray[self.selectItem!].EndTime ?? ""
            }else{
                s = dic["startTime"]
                e = dic["endTime"]
                var s1 = s?.replacingOccurrences(of: ":", with: "", options: String.CompareOptions.literal, range: nil)
                var e1 = e?.replacingOccurrences(of: ":", with: "", options: String.CompareOptions.literal, range: nil)
                if (e1 as NSString?)?.doubleValue ?? 0 < (s1 as NSString?)?.doubleValue ?? 0{
                    IsLastDay = true
                }
                //s?.getSubstring(<#T##start: Int##Int#>, end: <#T##Int#>)
            }
            var IsDefault = self.timeArray[self.selectItem!].IsDefault ?? false
            var order = self.selectItem
            var operate:[String:Any] = ["ID":id,"Form":["WorkTimeQuantumName":workTimeQuantumName,"BeginTime":s ?? "","EndTime":e ?? "","IsLastDay":IsLastDay,"IsDefault":IsDefault,"Order":order ?? 0]]
            
            do{
                let resultstr = try JSONSerialization.data(withJSONObject: operate, options: [])
                
                let json=(String.init(data: resultstr, encoding: .utf8))!
                print(json)
                
                var params:[String:Any] = ["pageName":"KouFine.Container.Form","orderConfigId":"a840da05-a150-bada-700e-9de7fe386801","orderId":id,"jsonData":json,"operate":operatetype]
                
                MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .KQTIMESET, params: &params, type: KQTimeSet.self, success: { (bean,_) in
                    //QWHudDiss(self.view)
                    if self.isedit{
                        QWHudDiss(self.timeDialog.contentview)
                    }else{
                        QWHudDiss(self.view)
                    }
                    
                    guard let b = bean as? KQTimeSet else{
                        return
                    }
                    if b.State == "OK"{
                        
                        if self.isedit{
                            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+2, execute: {
                                self.timeDialog.dismiss()
                            })
                            QWTextonlyHud("处理成功", target: self.timeDialog.contentview)
                        }else{
                            self.timeDialog.dismiss()
                            QWTextonlyHud("处理成功", target: self.view)
                        }
                        
                        
                        self.setupTimeIntervalData()
                    }else{
                        if self.isedit{
                            QWTextonlyHud(b.Msg ?? "", target: self.timeDialog.contentview)
                        }else{
                            QWTextonlyHud(b.Msg ?? "", target: self.view)
                        }
                    }
                }, error: { (error) in
                    //QWHudDiss(self.view)
                    if operatetype == 2{
                        //您设置的考勤时段超过了13小时，工作时段过长，请重新设置
                        if self.isedit{
                            QWHudDiss(self.timeDialog.contentview)
                            QWTextonlyHud("您设置的考勤时段超过了13小时，工作时段过长，请重新设置!", target: self.timeDialog.contentview)
                        }else{
                        QWHudDiss(self.view)
                            QWTextonlyHud("您设置的考勤时段超过了13小时，工作时段过长，请重新设置!", target: self.view)
                         }
                        
                    }else{
                        if self.isedit{
                            QWHudDiss(self.timeDialog.contentview)
                            QWTextonlyHud("该考勤时间段已有关联，不能删除", target: self.timeDialog.contentview)
                        }else{
                            QWHudDiss(self.view)
                            QWTextonlyHud("该考勤时间段已有关联，不能删除", target: self.view)
                        }
                        
                        
                    }
                   
                })
                
            }catch{
                print("error")
                QWHudDiss(self.view)
                QWTextonlyHud("数据异常", target: self.view)
            }
    }
    
    lazy var datePicker:UIDatePicker = {
        let datePicker = UIDatePicker.init()
        datePicker.frame = CGRect(x: 0, y: 10, width: SCREEN_WIDTH-20, height: self.emptyStr.getMessageHeight()*1.2)
        datePicker.locale = NSLocale.init(localeIdentifier: "zh_CN") as Locale
        datePicker.datePickerMode = .time
        //datePicker.backgroundColor = UIColor.white
        datePicker.setDate(NSDate.init() as Date, animated: true)
        return datePicker
    }()
    @IBOutlet weak var tableView: UITableView!
    var selectItemModel:TimeIntervalModel?
    lazy var timeArray : [TimeIntervalModel] = [TimeIntervalModel]()
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        WWProgressHUD.dismiss()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        //self.setupGetUdid()
        self.navigationItem.title = "考勤时段管理"
        
        self.isTomorror = false
        self.setupTimeIntervalData()
        self.tableView.delegate = self
        self.tableView.dataSource = self
        //self.tableView.separatorStyle = .none
        view.backgroundColor = UIColor.init(red: 233/255.0, green: 233/255.0, blue: 233/255.0, alpha: 1)
        self.tableView.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10)
        self.tableView.separatorInset = UIEdgeInsets.zero
        self.tableView.separatorStyle = .singleLine
        self.tableView.separatorColor = UIColor.init(red: 233/255.0, green: 233/255.0, blue: 233/255.0, alpha: 1)
        self.tableView.backgroundColor = UIColor.init(red: 233/255.0, green: 233/255.0, blue: 233/255.0, alpha: 1)
        let footView = TimeIntervalFootView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 186))
        footView.addTimeInterval.addTarget(self, action: #selector(addTimeIntervalButtonClick), for: .touchUpInside)
        self.tableView.tableFooterView = footView
        
        self.tableView.register(UINib.init(nibName: "TimeIntervalCell", bundle: nil), forCellReuseIdentifier: "time")
    }
    @objc fileprivate func addTimeIntervalButtonClick(){
        let lastModel = self.timeArray.last
        var number : String?
        if ((lastModel?.Order) != nil) {
             number = String((lastModel?.Order)!+1)
        }else{
            number=""
        }
        let titleStr = "时段" + number!
        self.timeAlert = TWLAlertView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
        
        self.custom = LCTimeSelectView.init(frame: CGRect(x: 0, y: 0, width: 280, height: 192))
        //custom?.titleLabel.text = titleStr
        self.custom?.amTimeButton.addTarget(self, action: #selector(amTimeButtonClick), for: .touchUpInside)
        self.custom?.pmTimeButton.addTarget(self, action: #selector(pmTimeButtonClick), for: .touchUpInside)
        //self.custom?.removeButton.addTarget(self, action: #selector(removeAlert), for: .touchUpInside)
        //self.custom?.makeSureButton.addTarget(self, action: #selector(makeSureTimeClick), for: .touchUpInside)
        //let tomoTap = UITapGestureRecognizer.init(target: self, action: #selector(tomoSelectClick(_:)))
        //self.custom?.tomoSelectView.addGestureRecognizer(tomoTap)
        self.timeAlert?.initWithCustomView(self.custom, frame: CGRect(x: 0, y: 0, width: 280, height: 192))
        let keyWindow = UIApplication.shared.keyWindow
        self.startTime = "08:00"
        self.endTime = "17:00"
        
        self.addAlert = CustomDialog(frame: CGRect.zero, _title: titleStr, _customview: self.custom!, _customHeight: 90, _cancelclick: {
            print("取消")
            self.addAlert?.dismiss()
        }, _submitclick: {
            print("queding")
            self.setupGetUdid()
            
        })
        self.isedit = false
        self.addAlert?.show()
        //keyWindow?.addSubview(self.timeAlert!)
    }
     func makeSureTimeClick(){
        
        guard let gid = self.guid else{
            WWProgressHUD.error("错误数据!")
            return
        }
        let lastModel = self.timeArray.last
        guard ((lastModel?.Order) != nil) else {
            WWProgressHUD.error("错误数据!")
            return
        }
        let number = String((lastModel?.Order)!+1)
        guard (self.startTime != nil) && (self.endTime != nil) else {
            WWProgressHUD.error("错误数据!")
            return
        }
        do{
        let jsonStr = [
            "ID": gid,//同OrderID
            "Form": [
                "WorkTimeQuantumName": "时段" + number,//时间段名称
                "BeginTime": self.startTime!,//开始时间
                "EndTime": self.endTime!,//结束时间
                "IsLastDay": isTomorror!,//是否第二天，如果截止小于起始，为第二天。
                "IsDefault": false,//是否默认时间段,后台会判断
                "Order": (lastModel?.Order)!+1//与名称旁边的编号一致，默认1开始
            ]
            ] as [String : Any]
       //let classJsonStr : String = self.getJSONStringFromDictionary(dictionary: jsonStr as NSDictionary)
        let data = try JSONSerialization.data(withJSONObject: jsonStr, options: [])
        let resultstr=(String.init(data: data, encoding: .utf8))!

        guard let accountId = WWUser.sharedInstance.accountId else{
            WWProgressHUD.error("错误数据!")
            return
        }
        print(accountId)
        QWTextWithStatusHud("正在添加中...", target: self.addAlert!)
        //WWProgressHUD.showWithStatus("正在添加中...")
        LCAPiMainManager.request(.AddTimeInterval(orderId: gid, jsonData: resultstr, operate: "1", AccountId: accountId)) { (result) in
            //self.addAlert?.dismiss()
            //WWProgressHUD.dismiss()
            QWHudDiss(self.addAlert!)
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                guard (jsonString["State"]) as! String == "OK" else{
                    QWTextonlyHud((jsonString["Msg"] as? String) ?? "", target: self.addAlert!)
                    return
                }
                self.addAlert?.dismiss()
                QWTextonlyHud("保存成功", target: self.addAlert!)
                DispatchQueue.main.asyncAfter(wallDeadline: DispatchWallTime.now()+1.5, execute: {
                    self.setupTimeIntervalData()
                })
                
                //self.timeAlert?.cancleView()
               // WWProgressHUD.dismiss()
            }
            }
            
        }catch let error{
                
        }
    }
    /*@objc fileprivate func tomoSelectClick(_ tap:UITapGestureRecognizer){
        if self.isTomorror == false{
            self.isTomorror = true
            self.custom?.markView.image = UIImage.init(named: "lc_fangxin1")
        }else{
            self.isTomorror = false
            self.custom?.markView.image = UIImage.init(named: "lc_fangxin2")
        }
    }

    @objc fileprivate func removeAlert(){
        self.timeAlert?.cancleView()
    }*/
    @objc fileprivate func amTimeButtonClick(){
        
        self.datePicker.removeTarget(self, action: #selector(pmchangeDate(_:)), for: .valueChanged)
        //self.datePicker.removeFromSuperview()
        datePicker.addTarget(self, action: #selector(amchangeDate(_:)), for: UIControlEvents.valueChanged)
        
        self.present(self.actionsheet, animated: true, completion: nil)
        //self.actionsheet.view.addSubview(self.datePicker)
        //self.timeAlert?.addSubview(datePicker)
        //self.timeAlert?.bringSubview(toFront: datePicker)
    }
    @objc fileprivate func amchangeDate(_ datePicker : UIDatePicker){
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH:mm"
        self.startTime = dateFormatter.string(from: datePicker.date)
        //self.custom?.amTimeButton.setTitle(self.startTime, for: .normal)
    }
    
    @objc fileprivate func pmTimeButtonClick(){
        self.datePicker.removeTarget(self, action: #selector(amchangeDate(_:)), for: .valueChanged)
        //self.datePicker.removeFromSuperview()
        
        datePicker.addTarget(self, action: #selector(pmchangeDate(_:)), for: UIControlEvents.valueChanged)
        self.present(self.actionsheet, animated: true, completion: nil)
        //self.timeAlert?.addSubview(datePicker)
        //self.timeAlert?.bringSubview(toFront: datePicker)
    }
    
    @objc fileprivate func pmchangeDate(_ datePicker : UIDatePicker){
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH:mm"
        self.endTime = dateFormatter.string(from: datePicker.date)
        //self.custom?.pmTimeButton.setTitle(self.endTime, for: .normal)
    }
    
    fileprivate func setupTimeIntervalData(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        LCAPiMainManager.request(.CheckTimeInterVal(start: 0, limit: 200, AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                guard (jsonString["State"]) as! String == "OK" else{
                    return
                }
                guard let resultDic = jsonString["Result"] as? [String: AnyObject] else{
                    return
                }
                guard let itemsArray = resultDic["Items"] as? NSArray else{
                    return
                }
                print(jsonString)
                self.timeArray = Mapper<TimeIntervalModel>().mapArray(JSONObject: itemsArray)!
                print(self.timeArray)
               self.tableView.reloadData()
            }
        }
    }

    fileprivate func setupGetUdid(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        LCAPiMainManager.request(.GETLCNewGuid(number: 1, AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                guard (jsonString["Status"]) as! String == "OK" else{
                    return
                }
                self.guid = (jsonString["Guid"] as! String)
                self.makeSureTimeClick()
            }
        }
        
    }
    fileprivate func getJSONStringFromDictionary(dictionary:NSDictionary) -> String {
        if (!JSONSerialization.isValidJSONObject(dictionary)) {
            print("无法解析出JSONString")
            return ""
        }
        let data : NSData! = try? JSONSerialization.data(withJSONObject: dictionary, options: []) as NSData!
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
        return JSONString! as String
        
    }
}
extension TimeIntervalManagerViewController : UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.timeArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell : TimeIntervalCell = tableView.dequeueReusableCell(withIdentifier: "time") as! TimeIntervalCell
        cell.setupModelData(self.timeArray[indexPath.row])
        cell.selectionStyle = .none
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        //let item = self.timeArray[indexPath.row]
        self.selectItemModel = self.timeArray[indexPath.row]
        self.selectItem = indexPath.row
        
        if self.selectItemModel?.IsDefault == true{
            self.timeDialog.titlename.text = "默认时段"
            //QWTextonlyHud("默认时段不能删除", target: self.view)
            //self.timeDialog.show()
        }else{
            self.timeDialog.titlename.text = "时段"+String(self.selectItemModel?.Order ?? 0)
            
        }
        
        if self.selectItemModel?.BeginTime != nil{
            self.timeDialog.startTime.text = (self.selectItemModel?.BeginTime ?? "").getSubstring(11, end: 16)
            self.timeDialog.startTimeStr = (self.selectItemModel?.BeginTime ?? "").getSubstring(11, end: 16)
        }else{
            self.timeDialog.startTime.text = ""
        }
        if self.selectItemModel?.EndTime != nil{
            self.timeDialog.endTime.text = self.selectItemModel?.EndTime?.getSubstring(11, end: 16)
            self.timeDialog.endTimeStr = self.selectItemModel?.EndTime?.getSubstring(11, end: 16)
        }else{
            self.timeDialog.endTime.text = ""
        }
        self.isedit = true
        self.timeDialog.show()
        
    
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
}
